// 设置默认地址
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { addressId } = event
  
  // 直接使用openid作为用户标识
  if (!wxContext.OPENID) {
    return {
      success: false,
      message: '用户未登录'
    }
  }
  
  const userOpenid = wxContext.OPENID

  if (!addressId) {
    return {
      success: false,
      message: '地址ID不能为空'
    }
  }

  try {
    // 开启事务，确保数据一致性
    const transaction = await db.startTransaction()

    try {
      // 1. 将用户所有地址的默认状态设为false
      await transaction.collection('addresses')
        .where({
          userId: userOpenid
        })
        .update({
          data: {
            isDefault: false,
            updateTime: new Date()
          }
        })

      // 2. 将指定地址设为默认
      await transaction.collection('addresses')
        .doc(addressId)
        .update({
          data: {
            isDefault: true,
            updateTime: new Date()
          }
        })

      // 提交事务
      await transaction.commit()

      return {
        success: true,
        message: '设置默认地址成功'
      }
    } catch (error) {
      // 回滚事务
      await transaction.rollback()
      throw error
    }
  } catch (error) {
    console.error('设置默认地址失败:', error)
    return {
      success: false,
      message: '设置默认地址失败',
      error: error.message
    }
  }
}